/** 代理 */
function httpProxy(url,prot) {
    var Proxy =  java.net.Proxy;
    var InetSocketAddress = java.net.InetSocketAddress;
    var okhttp = new Packages.okhttp3.OkHttpClient.Builder().proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(url, prot)));
    http.__okhttp__.muteClient(okhttp);
}

function getCookie(url) {
    try {
        let cookieManager = android.webkit.CookieManager.getInstance();
        return cookieManager.getCookie(url) || '';
    } catch (e) {
        console.trace('获取cookie异常', e);
        return '';
    }
}
function getForJson(url) {
    try {
        let options = {
            method: 'GET',
            headers: {
                'Cookie': getCookie(url)
            }
        };
        let response = http.request(url, options);
        if (response.statusCode <200 || response.statusCode > 299) {
            console.log(response)
            throw new Error(response.statusCode + ": " + response.body.string());
        }
        return response.body.json();
    } catch (e) {
        console.trace(e);
        return {};
    }
}

function getForString(url, headers) {
    try {
        if (!headers) {
            headers = {};
        }
        headers['Cookie'] = getCookie(url);
        let options = {
            method: 'GET',
            headers: headers
        };
        let response = http.request(url, options);
        if (response.statusCode <200 || response.statusCode > 299) {
            console.log(response)
            throw new Error(response.statusCode + ": " + response.body.string());
        }
        return response.body.string();
    } catch (e) {
        console.trace(e);
        return {};
    }
}

function postForJson(url, data, headers) {
    try {
        if (!headers) {
            headers = {};
        }
        headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
        headers['Cookie'] = getCookie(url);
        let options = {
            method: 'POST',
            body: data || '',
            headers: headers
        };
        let response = http.request(url, options);
        // response = http.post(url, data, {})
        if (response.statusCode <200 || response.statusCode > 299) {
            console.log(JSON.stringify(response));
            throw new Error(response.statusCode + ": " + response.body.string());
        }
        return response.body.json();
    } catch (e) {
        console.trace(e);
        return {};
    }
}

module.exports = {
    httpProxy: httpProxy,
    getForJson: getForJson, 
    getForString: getForString,
    postForJson: postForJson
}